<template>
	<!-- 个人中心 -->
	<view class="my-center">
		<view class="content">
			<!--  头部 -->
			<view class="head">
				<view class="head-img" @click="handleAvatarClick">
					<image class="avatar"
						:src="isLoggedIn&&userInfo.avatar?userInfo.avatar:'/static/images/head_default.png'"
						mode="aspectFill"></image>
					<image class="vip" v-if="userInfo.authStatus == '1' || userInfo.authStatus == '2' "
						src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/home_vip.png" mode="widthFix">
					</image>
				</view>
				<view class="head-info">
					<view class="row">
						<view class="name" :class="isLoggedIn?'':'name-red'">
							<button @click="handleLogin">{{ isLoggedIn?userInfo.realName:'登录/注册' }}</button>
						</view>
						<view v-if="userInfo.srStatus !== '1'" class="authentication-status"
							@click="topage('/pages/rlrz/rlrz')">
							去实名<uni-icons type="right" size="14" color="#AC6C17"></uni-icons>
						</view>
						<view v-if="userInfo.srStatus == '1'" class="authentication-status authentication-status-yrz">
							已实名</view>
					</view>

					<view class="block-text">
						<view class="text-btn" @click="topage('/pages/membership/membership')">
							{{ (userInfo.userType == 'vip' || userInfo.userType == 'Svip')?'续约会员':'开通会员' }}
						</view>
						<view class="text">
							{{ userInfo.userType == '体验vip' 
    ? '体验vip' 
    : userInfo.userType == 'vip' 
        ? 'vip会员' 
        : userInfo.userType == 'Svip' 
            ? 'Svip会员' 
            : '您还未开通会员' 
}}
							{{ (userInfo.userType == '体验vip' || userInfo.userType == 'vip'  || userInfo.userType == 'Svip')? '至'+ formatTime(userInfo.authEndTimeCn):'' }}
						</view>
					</view>
				</view>
			</view>
			<!-- 开通会员 -->
			<view class="open-account" @click="topage('/pages/membership/membership')">
				<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/kthy_bg.png" mode="widthFix">
				</image>
				<view class="text">
					<view v-if="userInfo.authStatus !== '1' && userInfo.authStatus !== '2'" class="top">畅通合作 营收增倍</view>
					<view v-if="userInfo.authStatus !== '1' && userInfo.authStatus !== '2'" class="bottom">免费领取获客资料包
					</view>
					<view v-if="userInfo.authStatus == '1' || userInfo.authStatus == '2'" class="top1">打破信息壁垒 畅享无限资源
					</view>
					<view v-if="userInfo.authStatus == '1' || userInfo.authStatus == '2'" class="bottom1">超凡共享 · 价值之圈
					</view>
				</view>
			</view>
			<!-- 已经是会员 -->
			<!-- 	<view v-if="userInfo.authStatus == '1'" class="already-member"
				@click="topage('/pages/membership/membership')">
				<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/already_member.png"
					mode="widthFix" style="object-fit: cover;"></image>
				<view class="text">VIP至{{ formatDate(userInfo.authEndTime) }} <uni-icons type="right" size="12"
						color="#703D00"></uni-icons> </view>
			</view> -->

			<!-- 菜单 -->
			<view class="menu-list">
				<view class="row" @click="topage('/pages/my-card/my-card')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_wdmp@2x.png"
							mode="widthFix"></image>我的名片
					</view>
					<view class="right">
						分享名片<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="topage('/pages/complete-information/complete-information')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_wsxx@2x.png"
							mode="widthFix"></image>完善信息
					</view>
					<view class="right">
						去完善<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="topage('/pages/rlrz/rlrz')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_smrz@2x.png"
							mode="widthFix"></image>实名认证
					</view>
					<view class="right">
						立即实名<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<!-- 	<view class="row" @click="topage('/pages/my-purse/my-purse')">
					<view class="left">我的钱包</view>
					<view class="right">
						查看钱包<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view> -->
				<view class="row" @click="topage('/pages/my-group/my-group')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_wdtd@2x.png"
							mode="widthFix"></image>我的团队
					</view>
					<view class="right">
						查看团队<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="topage('/pages/my-publish/my-publish')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_wdfb@2x.png"
							mode="widthFix"></image>我的发布
					</view>
					<view class="right">
						查看<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="topage('/pages/my-xspx/my-xspx')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_wdfb@2x.png"
							mode="widthFix"></image>我的培训
					</view>
					<view class="right">
						查看<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="topage('/pages/promotional-poster/promotional-poster')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_tghb@2x.png"
							mode="widthFix"></image>推广海报
					</view>
					<view class="right">
						推广海报<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="topage('/pages/my-sqcwfws/my-sqcwfws')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_sqcwfws@2x.png"
							mode="widthFix"></image>我是服务商
					</view>
					<view class="right">
						立即申请<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view class="row" @click="showPopup('official')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_gfkf@2x.png"
							mode="widthFix"></image>官方客服
					</view>
					<view class="right">
						联系官方客服<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
				<view v-if="isLoggedIn" class="row" @click="showPopup('cancel')">
					<view class="left">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/grzx_zxzh@2x.png"
							mode="widthFix"></image>注销账号
					</view>
					<view class="right">
						立即注销<uni-icons type="right" size="14" color="#777"></uni-icons>
					</view>
				</view>
			</view>

		</view>
		<!-- 底部菜单 -->
		<tab-bar :selected='4'></tab-bar>
		<!-- 弹出框 -->
		<view class="popup" v-if="showPopupFlag">
			<view class="popup-mask"></view>
			<view class="popup-content" @longpress="handlePopupClick">
				<view class="top">
					<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/gfkf_bg.png" mode="widthFix">
					</image>
				</view>
				<!-- 	<view class="bottom">
					<view class="lf">
						<view class="text-sys">扫描二维码，添加客服企业微信</view>
						<view class="text-qywx">
							<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/qywx.png"
								mode="widthFix"></image>企业微信
						</view>
					</view>
					<view class="rt">
						<image src="https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/kefu.png" mode="widthFix">
						</image>
					</view>
				</view> -->
				<view class="close-btn" @click="closePopup">
					<uni-icons type="closeempty" size="20" color="#fff"></uni-icons>
				</view>
			</view>
		</view>
	</view>


</template>

<script>
	import TabBar from '../../components/TabBar.vue';
	import {
		parseDate
	} from '@/utils/date.js';
	export default {
		components: {
			TabBar
		},
		data() {
			return {
				showPopupFlag: false,
				groupUserId: uni.getStorageSync('groupUserId') || '',
				kefu: 'https://luntan.xiaouyf.cn/uecs-wechat/static/img/qianduan/gfkf_bg.png'
			}
		},
		computed: {
			// 从 Vuex 获取登录状态和用户信息
			isLoggedIn() {
				return this.$store.state.user.isLoggedIn;
			},
			userInfo() {
				console.log(this.$store.state.user.userInfo)
				return this.$store.state.user.userInfo;
			}
		},
		onLoad(options) {
			if (options && options.scene && !this.isLoggedIn) { // 扫码进来-可加入创建人的团队 前提没有注册过的新用户
				this.groupUserId = decodeURIComponent(options.scene); // 解码参数
				uni.setStorageSync('groupUserId', this.groupUserId);
				uni.redirectTo({
					url: '/pages/login/login'
				});
				return;
			}
			if (this.isLoggedIn && this.userInfo.guid) { // 如果有guid 根据guid获取用户信息
				this.getInfoGuid()
			}
			if (this.groupUserId && this.isLoggedIn && this.groupUserId !== this.userInfo.guid) {
				this.infoGroupCreate();
			}
			// 显示分享按钮
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			});
		},
		onShareAppMessage() {
			return {
				title: '百万助贷人资源对接价值之圈',
				path: '/pages/index/index'
			};
		},
		methods: {
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';

				// 处理日期格式，确保兼容iOS
				const formatDateStr = (str) => {
					// 将 "4/11/26 5:57 PM" 转换为 "2026/04/11 17:57:00"
					const parts = str.split(' ');
					const dateParts = parts[0].split('/');
					const timeParts = parts[1].split(':');
					const period = parts[2];

					// 处理年份（假设20开头的年份）
					const year = dateParts[2].length === 2 ? '20' + dateParts[2] : dateParts[2];
					const month = dateParts[0].padStart(2, '0');
					const day = dateParts[1].padStart(2, '0');

					// 处理时间
					let hours = parseInt(timeParts[0]);
					const minutes = timeParts[1].padStart(2, '0');

					if (period === 'PM' && hours < 12) {
						hours += 12;
					} else if (period === 'AM' && hours === 12) {
						hours = 0;
					}

					return `${year}/${month}/${day} ${hours.toString().padStart(2, '0')}:${minutes}:00`;
				};

				try {
					// 先尝试格式化日期字符串
					const formattedStr = formatDateStr(dateStr);
					const date = new Date(formattedStr);

					// 如果日期无效，返回原始字符串
					if (isNaN(date.getTime())) {
						return dateStr;
					}

					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');

					return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				} catch (error) {
					console.error('日期格式化错误:', error);
					return dateStr;
				}
			},
			// 格式化时间，只显示年月日时分
			formatTime(dateStr) {
				if (!dateStr) return '';
				try {
					const date = new Date(dateStr);
					if (isNaN(date.getTime())) return dateStr;

					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');

					return `${year}-${month}-${day} ${hours}:${minutes}`;
				} catch (error) {
					console.error('时间格式化错误:', error);
					return dateStr;
				}
			},
			// 如果有guid 根据guid获取用户信息
			getInfoGuid() {
				const requestData = {
					guid: this.userInfo.guid
				}
				this.$api.getInfo(requestData).then(res => {
					if (res.succ) {
						// 判断有没有维护信息
						const isChinese = /^[\u4e00-\u9fa5]+$/.test(res.data.realName);
						if (!isChinese && res.data.avatar === null) {
							uni.showModal({
								title: '提示',
								showCancel: false,
								maskClick: false,
								content: '请先完善信息',
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/complete-information/complete-information'
										});
									}
								}
							});
						}
						// 判断用户类型
						let userType = '普通用户';
						if (res.data.authStatus == '0') {
							const endTime = parseDate(res.data.authEndTimeCn);
							const now = new Date();
							if (endTime > now) {
								userType = '体验vip';
							}
						} else if (res.data.authStatus == '1') {
							userType = 'vip';
						} else if (res.data.authStatus == '2') {
							userType = 'Svip';
						}
						// 将用户类型添加到用户信息中
						res.data.userType = userType;
						this.$store.dispatch('user/setUserInfo', res.data);
						this.$store.dispatch('user/setLoginStatus', true);
					} else {
						if (res.msg === '该账号未绑定！') {
							// 清空所有存储的数据
							this.$store.dispatch('user/setUserInfo', {});
							this.$store.dispatch('user/setLoginStatus', false);
							uni.clearStorageSync();
							uni.showToast({
								title: '账号未绑定，请重新登录',
								icon: 'none'
							});
							A
						}
					}
				}).catch(err => {
					console.error(err);
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					});
				})
			},
			// 扫码进来-可加入创建人的团队
			infoGroupCreate() {
				const requestData = {
					groupUserId: this.userInfo.guid, // 扫码人的id
					userId: this.groupUserId, // 团长id
				}
				this.$api.infoGroupCreate(requestData).then(res => {
					if (res.succ) {
						this.groupUserId = '';
						uni.removeStorageSync('groupUserId');
					} else {
						uni.showToast({
							title: res.msg || '操作失败，请重试',
							icon: 'none'
						});
					}
					uni.hideLoading();
				}).catch(err => {
					console.error(err);
					uni.hideLoading();
				})
			},
			// 跳转页面
			topage(to) {
				// 检查登录状态
				if (!this.isLoggedIn) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					// 跳转到登录页面
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login'
						});
					}, 1500);
					return;
				}
				
				uni.showLoading({
					title: '加载中...'
				});

				setTimeout(() => {
					uni.hideLoading();
					uni.navigateTo({
						url: to,
						fail: (err) => {
							if (err.errMsg.includes('timeout')) {
								uni.switchTab({
									url: to,
									fail: () => {
										uni.showToast({
											title: '页面跳转失败，请重试',
											icon: 'none'
										});
									}
								});
							} else {
								uni.showToast({
									title: '页面跳转失败，请重试',
									icon: 'none'
								});
							}
						}
					});
				}, 100);
			},
			showPopup(type) {
				this.showPopupFlag = true;
			},
			closePopup() {
				this.showPopupFlag = false;
			},
			// 处理弹出框长按事件
			handlePopupClick() {
				// 预览图片，用户可以在预览界面长按识别二维码
				wx.previewImage({
					urls: [this.kefu],
					current: this.kefu
				});
			},
			checkAuthStatus(res) {
				if (res.data.authEndTimeCn && res.data.authEndTimeCn !== '0') {
					const endTime = parseDate(res.data.authEndTimeCn);
					const now = new Date();
					if (endTime > now) {
						// ... existing code ...
					}
				}
			},
			handleLogin() {
				if (!this.isLoggedIn) {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}
			},
			// 处理头像点击
			handleAvatarClick() {
				if (!this.isLoggedIn) {
					uni.showToast({
						title: '请先登录后查看个人信息',
						icon: 'none'
					});
					// 跳转到登录页面
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login'
						});
					}, 1500);
					return;
				}
				// 已登录时跳转到个人信息页面
				uni.navigateTo({
					url: '/pages/my-information/my-information'
				});
			}
		}
	}
</script>

<style lang="less">
	.my-center {
		height: 100%;
		display: flex;
		flex-direction: column;
		background: linear-gradient(180deg, #FAEBDB 0%, rgba(255, 247, 238, 0) 500rpx);

		.content {
			z-index: 2;
			position: relative;
			flex: 1;
			padding: 0 20rpx;
			overflow: auto;

			// 头部
			.head {
				display: flex;
				align-items: center;
				margin: 40rpx 10rpx;

				.head-img {
					position: relative;
					width: 120rpx;
					height: 120rpx;
					border: 6rpx solid #fff;
					border-radius: 100%;

					.avatar {
						width: 120rpx;
						height: 120rpx;
						object-fit: cover;
						border-radius: 100%;
					}

					.vip {
						width: 38rpx;
						height: 31rpx;
						position: absolute;
						right: -10rpx;
						top: 4rpx;
					}
				}

				.head-info {
					display: flex;
					flex-direction: column;
					margin-left: 20rpx;

					.row {
						display: flex;
						align-items: center;

						.name {
							font-size: 32rpx;
							color: #000;
							font-weight: bold;
							margin-left: 10rpx;

							button {
								background: none;
								border: none;
								outline: none;
								padding: 0;
								line-height: 1;

								&::after {
									border: none;
								}
							}

							&.name-red {
								button {
									color: #DB943C;
								}

							}
						}

						.authentication-status {
							position: absolute;
							top: 40rpx;
							right: 0;
							width: 160rpx;
							height: 64rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							background: #FFEFD9;
							border-radius: 20rpx 0rpx 0rpx 20rpx;
							font-size: 30rpx;
							color: #AC6C17;
						}
					}

					.block-text {
						display: flex;
						align-items: center;
						margin-top: 35rpx;

						.text-btn {
							display: inline-flex;
							width: 115rpx;
							height: 56rpx;
							align-items: center;
							justify-content: center;
							font-size: 28rpx;
							padding: 0 20rpx;
							color: #FFFFFF;
							background: linear-gradient(180deg, #F3B359 0%, #EC6A34 100%);
							border-radius: 44rpx 44rpx 44rpx 44rpx;
							margin-right: 15rpx;
						}

						.text {
							font-size: 28rpx;
							color: #AC6C17;
						}

					}
				}
			}

			// 开通会员
			.open-account {
				z-index: 2;
				position: relative;
				margin: 30rpx 10rpx 20rpx;

				image {
					z-index: 1;
					position: relative;
					width: 100%;
					height: 300rpx;
				}

				.text {
					z-index: 2;
					position: absolute;
					left: 0;
					top: 0;
					width: 100%;
					height: 300rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.top {
						font-size: 60rpx;
						font-weight: bold;
						margin-bottom: 20rpx;
						background: linear-gradient(136deg, #FAF6E2 0%, #EBBF92 100%);
						-webkit-background-clip: text;
						/* 关键属性：文本裁剪 */
						background-clip: text;
						color: transparent;
						/* 隐藏原始文字颜色 */
					}

					.top1 {
						font-size: 46rpx;
						font-weight: bold;
						margin-bottom: 20rpx;
						background: linear-gradient(136deg, #FAF6E2 0%, #EBBF92 100%);
						-webkit-background-clip: text;
						/* 关键属性：文本裁剪 */
						background-clip: text;
						color: transparent;
						/* 隐藏原始文字颜色 */
					}

					.bottom {
						width: 384rpx;
						height: 80rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 32rpx;
						color: #FFFFFF;
						margin-top: 25rpx;
						background: linear-gradient(180deg, #F3B359 0%, #EC6A34 100%);
						border-radius: 44rpx 44rpx 44rpx 44rpx;
					}

					.bottom1 {
						font-size: 36rpx;
						margin: 30rpx 0 20rpx;
						color: #FCCD8E;
					}
				}
			}

			// 菜单
			.menu-list {
				z-index: 1;
				position: relative;
				background: #fff;
				margin: 0 10rpx 30rpx;
				padding: 20rpx 10rpx;
				box-shadow: 0rpx 0rpx 20rpx 1rpx rgba(0, 0, 0, 0.1);
				border-radius: 10rpx;

				.row {
					position: relative;
					display: flex;
					justify-content: space-between;
					align-items: center;

					// &:after {
					// 	content: '';
					// 	position: absolute;
					// 	bottom: 0;
					// 	left: 0;
					// 	width: 100%;
					// 	height: 1px;
					// 	background-color: #e8e8e8;
					// 	transform: scaleY(0.5);
					// }

					&:last-child:after {
						display: none;
					}

					.left {
						display: flex;
						align-items: center;
						font-size: 33rpx;
						padding: 35rpx 10rpx;
						color: #333;

						image {
							width: 44rpx;
							height: 44rpx;
							margin-right: 16rpx;
						}
					}

					.right {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: flex-end;
						color: #777;
						font-size: 30rpx;

						uni-icons {
							margin-left: 12rpx;
						}
					}
				}
			}
		}
	}

	.popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;

		.popup-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.8);
		}

		.popup-content {
			position: absolute;
			width: 80%;
			top: 43%;
			left: 50%;
			transform: translate(-50%, -50%);
			border-radius: 10rpx;
			background: transparent;

			.top {
				width: 100%;
				display: flex;
				justify-content: center;

				image {
					width: 100%;
					object-fit: cover;
					border: 0;
					border-radius: 10rpx;
				}
			}

			.bottom {
				display: flex;
				justify-content: space-between;
				padding: 30rpx 30rpx;
				background: #FFEFD9;
				border-radius: 5rpx;

				.lf {
					display: flex;
					flex-direction: column;
					justify-content: center;


					.text-sys {
						font-size: 30rpx;
						color: #AC6C17;
						font-weight: bold;
						margin-bottom: 20rpx;
					}

					.text-qywx {
						font-size: 28rpx;
						color: #AC6C17;
						margin-top: 20rpx;
						display: flex;
						align-items: center;

						image {
							width: 40rpx;
							height: 40rpx;
							margin-right: 10rpx;
						}
					}
				}

				.rt {
					display: flex;
					align-items: center;

					image {
						width: 200rpx;
						height: 200rpx;
						object-fit: cover;
					}
				}

			}

			.close-btn {
				position: absolute;
				bottom: -80rpx;
				left: 50%;
				width: 50rpx;
				height: 50rpx;
				transform: translateX(-50%);
				border: 2px solid #fff;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>